package com.wkq.net.util;

import android.util.Base64;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;

/**
 * 作者:吴奎庆
 * <p>
 * 时间:2021/2/19
 * <p>
 * 用途:
 */


public
 class MangoUtils {
    public static String md5(final String toEncrypt) {

        if (toEncrypt == null) {
            return null;
        }

        try {
            final MessageDigest digest = MessageDigest.getInstance("md5");
            digest.update(toEncrypt.getBytes());
            final byte[] bytes = digest.digest();
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytes.length; i++) {
                sb.append(String.format("%02X", bytes[i]));
            }
            return sb.toString().toLowerCase();

        } catch (Exception exc) {
            return null;
        }
    }

    public static String decodeWithBase64AndInflate(String content) {
        byte[] decodedQuestions = Base64.decode(content, Base64.DEFAULT);

        byte[] returnValues = null;
        Inflater inflater = new Inflater();

        int numberOfBytesToDecompress = decodedQuestions.length;

        inflater.setInput(decodedQuestions, 0, numberOfBytesToDecompress);

        List<Byte> bytesDecompressedSoFar = new ArrayList<Byte>();

        try
        {
            while (!inflater.needsInput())
            {
                byte[] bytesDecompressedBuffer = new byte[numberOfBytesToDecompress];

                int numberOfBytesDecompressedThisTime =
                        inflater.inflate(bytesDecompressedBuffer);

                for (int b = 0; b < numberOfBytesDecompressedThisTime; b++) {
                    bytesDecompressedSoFar.add(bytesDecompressedBuffer[b]);
                }
            }

            returnValues = new byte[bytesDecompressedSoFar.size()];
            for (int b = 0; b < returnValues.length; b++) {
                returnValues[b] = bytesDecompressedSoFar.get(b);
            }

            inflater.end();
            return new String(returnValues, 0, returnValues.length, "UTF-8");

        } catch (DataFormatException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return "";
    }
}
